package com.hgyc.mom.qms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.base.entity.Material;
import com.hgyc.mom.base.service.MaterialService;
import com.hgyc.mom.common.enums.SysOrderTypeEnum;
import com.hgyc.mom.common.enums.SysYesNoEnum;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.qms.entity.QmsIndex;
import com.hgyc.mom.qms.entity.QmsIqc;
import com.hgyc.mom.qms.entity.QmsIqcDetail;
import com.hgyc.mom.qms.entity.QmsTemplateIndex;
import com.hgyc.mom.qms.mapper.QmsIqcMapper;
import com.hgyc.mom.qms.service.QmsIndexService;
import com.hgyc.mom.qms.service.QmsIqcDetailService;
import com.hgyc.mom.qms.service.QmsIqcService;
import com.hgyc.mom.qms.service.QmsTemplateIndexService;
import com.hgyc.mom.qms.vo.QmsIqcVO;
import com.hgyc.mom.tool.strategy.AutoCodeUtil;
import com.hgyc.mom.wms.entity.WmsPurchaseReceiptDetail;
import com.hgyc.mom.wms.entity.WmsStockInDetail;
import com.hgyc.mom.wms.enums.StockInStatusEnum;
import com.hgyc.mom.wms.service.WmsPurchaseReceiptDetailService;
import com.hgyc.mom.wms.service.WmsStockInService;
import com.hgyc.mom.wms.vo.WmsPurchaseReceiptVO;
import com.hgyc.mom.wms.vo.WmsStockInVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 来料检验单Service业务层实现
 *
 * @author fwj
 * @since 2025-09-27
 */
@Slf4j
@Service
public class QmsIqcServiceImpl extends ServiceImpl<QmsIqcMapper, QmsIqc> implements QmsIqcService {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private QmsTemplateIndexService qmsTemplateIndexService;

    @Autowired
    private QmsIndexService qmsIndexService;

    @Autowired
    private WmsPurchaseReceiptDetailService wmsPurchaseReceiptDetailService;

    @Autowired
    private WmsStockInService wmsStockInService;

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private QmsIqcDetailService qmsIqcDetailService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveIqc(QmsIqcVO qmsIqcVO) {
        qmsIqcVO.setCode(autoCodeUtil.genSerialCode("iqc_code", null));
        save(qmsIqcVO);

        //新增来料检验项明细
        List<QmsIqcDetail> iqcDetails = qmsIqcVO.getAddIqcDetails();
        if (!CollectionUtils.isEmpty(iqcDetails)) {
            iqcDetails.forEach(item -> {
                item.setId(null);
                item.setIqcId(qmsIqcVO.getId());
            });
            qmsIqcDetailService.saveBatch(iqcDetails);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateIqc(QmsIqcVO qmsIqcVO) {
        // TODO 其他逻辑
        updateById(qmsIqcVO);

        //删除来料检验项明细
        if (!CollectionUtils.isEmpty(qmsIqcVO.getDeleteIqcDetailIds())) {
            qmsIqcDetailService.removeBatchByIds(qmsIqcVO.getDeleteIqcDetailIds());
        }

        //新增来料检验项明细
        List<QmsIqcDetail> iqcDetails = qmsIqcVO.getAddIqcDetails();
        if (!CollectionUtils.isEmpty(iqcDetails)) {
            iqcDetails.forEach(item -> {
                item.setId(null);
                item.setIqcId(qmsIqcVO.getId());
            });
            qmsIqcDetailService.saveBatch(iqcDetails);
        }

        //更新来料检验项明细
        if (!CollectionUtils.isEmpty(qmsIqcVO.getUpdateIqcDetails())) {
            List<QmsIqcDetail> updateIqcDetails = qmsIqcVO.getUpdateIqcDetails();
            qmsIqcDetailService.updateBatchById(updateIqcDetails);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeIqc(List<Long> ids) {
        // TODO 其他逻辑
        removeByIds(ids);
        //删除来料检验项明细
        qmsIqcDetailService.deleteBatchByParentIds(ids);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<QmsIqc> qmsIqcList, boolean updateSupport) {
        if (qmsIqcList == null || qmsIqcList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + qmsIqcList.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + qmsIqcList.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("来料检验单导入失败", e);
            throw new BizException("来料检验单导入失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void inspect(WmsPurchaseReceiptVO wmsPurchaseReceiptVO) {
        List<WmsPurchaseReceiptDetail> inspectDetails = wmsPurchaseReceiptVO.getInspectDetails();
        for (WmsPurchaseReceiptDetail inspectDetail : inspectDetails) {
            Long materialId = inspectDetail.getMaterialId();
            Material material = materialService.getById(materialId);

            // 1. 判断物料是否免检
            if (material == null && SysYesNoEnum.N.getValue().equals(material.getInspectExempted())) {
                // 2. 根据检验模板获取检验项目
                List<QmsTemplateIndex> indexList = qmsTemplateIndexService.getIqcIndexByMaterial(materialId);

                // 3. 创建检验单据
                QmsIqcVO qmsIqcVO = new QmsIqcVO();
                qmsIqcVO.setSourceId(wmsPurchaseReceiptVO.getId());
                qmsIqcVO.setSourceCode(wmsPurchaseReceiptVO.getReceiptCode());
                qmsIqcVO.setSourceType(SysOrderTypeEnum.RECEIVING_ORDER.getValue());
                qmsIqcVO.setSourceLineId(inspectDetail.getId());
                qmsIqcVO.setSupplierId(wmsPurchaseReceiptVO.getSupplierId());
                qmsIqcVO.setMaterialId(materialId);

                List<QmsIqcDetail> details = new ArrayList<>();
                for (QmsTemplateIndex templateIndex : indexList) {
                    QmsIqcDetail detail = new QmsIqcDetail();
                    Long indexId = templateIndex.getIndexId();
                    QmsIndex qmsIndex = qmsIndexService.getById(indexId);
                    detail.setIndexId(templateIndex.getId());
                    detail.setIndexCode(qmsIndex.getIndexCode());
                    detail.setIndexName(qmsIndex.getIndexName());
                    detail.setQcTool(qmsIndex.getQcTool());
                    detail.setCheckMethod(templateIndex.getCheckMethod());
                    detail.setStanderVal(templateIndex.getStanderVal());
                    detail.setUnitOfMeasure(templateIndex.getUnitOfMeasure());
                    detail.setThresholdMax(templateIndex.getThresholdMax());
                    detail.setThresholdMin(templateIndex.getThresholdMin());
                    details.add(detail);
                }
                qmsIqcVO.setAddIqcDetails(details);

                saveIqc(qmsIqcVO);

                // 4. 回写来料明细的已送检数量
                BigDecimal inspectedQty = inspectDetail.getInspectedQty() == null ? BigDecimal.ZERO : inspectDetail.getInspectedQty();
                inspectedQty = inspectedQty.add(inspectDetail.getToInspectQty() == null ? BigDecimal.ZERO : inspectDetail.getToInspectQty());
                inspectDetail.setInspectedQty(inspectedQty);
                inspectDetail.setToInspectQty(BigDecimal.ZERO);
                wmsPurchaseReceiptDetailService.updateById(inspectDetail);

            } else {
                // 如果是免检，直接创建入库单
                WmsStockInVO wmsStockInVO = new WmsStockInVO();
                wmsStockInVO.setSourceCode(wmsPurchaseReceiptVO.getReceiptCode());
                wmsStockInVO.setType(SysOrderTypeEnum.RECEIVING_ORDER.getValue());
                wmsStockInVO.setWarehouseId(wmsPurchaseReceiptVO.getWarehouseId());
                wmsStockInVO.setStatus(StockInStatusEnum.CREATE.getValue());

                List<WmsStockInDetail> details = new ArrayList<>();
                WmsStockInDetail detail = new WmsStockInDetail();
                detail.setMaterialId(materialId);
                detail.setQtyPending(inspectDetail.getActuallyQty());
                detail.setQtyReceived(BigDecimal.ZERO);
                detail.setStatus(StockInStatusEnum.CREATE.getValue());
                wmsStockInVO.setAddStockInDetails(details);

                wmsStockInService.saveStockIn(wmsStockInVO);
            }
        }
    }
}
